package com.huafeng.security;

import com.huafeng.commonutil.JwtHelper;
import com.huafeng.model.base.Result;
import com.huafeng.model.enums.ResultCodeEnum;
import com.huafeng.commonutil.ResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * @author 花风
 * @date 2023/8/20 18:51
 * @Description token解析器
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //如果是登录接口，直接放行
        if("/admin/system/sysUser/login".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }

        Authentication authentication = getAuthentication(request);
        if (authentication != null){
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request,response);
        } else {
            ResponseUtils.out(response, new Result(ResultCodeEnum.PERMISSION));
        }
    }

    private Authentication getAuthentication(HttpServletRequest request){
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token) || StringUtils.isBlank(token)){
            // 如果token为空，说明未登录或登录过期，需要重新登录
            return null;
        }
        // 解析token，获取用户信息
        String userName = JwtHelper.getUserName(token);
        return new UsernamePasswordAuthenticationToken(userName,null, Collections.emptyList());
    }
}
